package com.miguo.db;

import android.content.Context;

import com.miguo.app.AppContext;
import com.miguo.bean.CategoryBean;
import com.miguo.db.CategoryDao.Properties;

import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

public class CategoryDB {
    private static Context mContext;
    private static CategoryDB instance;

    private CategoryDao categoryDao;

    private CategoryDB() {
    }

    public static CategoryDB getInstance(Context context, boolean ClearSession) {
        if (instance == null) {
            instance = new CategoryDB();
            if (mContext == null) {
                mContext = context;
            }

            // 数据库对象
            DaoSession daoSession = AppContext.getDaoSession(mContext,
                    ClearSession);
            instance.categoryDao = daoSession.getCategoryDao();
        }
        return instance;
    }

    public List<CategoryBean> loadAll() {
        return categoryDao.loadAll();
    }

    public List<CategoryBean> findPid(Long pid) {
        QueryBuilder<CategoryBean> qb = categoryDao.queryBuilder();
        qb.where(Properties.Pid.eq(pid));
        qb.orderAsc(Properties.Ordid);// 排序依据
        return qb.list();
    }

    /**
     * insert or update noteList use transaction
     *
     * @param list
     */
    public void saveList(final List<CategoryBean> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        categoryDao.getSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < list.size(); i++) {
                    CategoryBean note = list.get(i);
                    categoryDao.insertOrReplace(note);
                }
            }
        });

    }

    public boolean isExist() {
        QueryBuilder<CategoryBean> qb = categoryDao.queryBuilder();
        return qb.buildCount().count() > 0 ? true : false;
    }

    /**
     * delete all
     */
    public void deleteAll() {
        categoryDao.deleteAll();
    }
}